<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>放大镜</title>
	<style type="text/css">
	*{padding:0px;margin:0px;}
	#small{width:400px;height:400px;border:solid 1px blue;position:absolute;left:100px;top:50px;overflow:hidden;cursor:move;}

	#big{width:400px;height:400px;position:absolute;left:600px;top:50px;overflow:hidden;display:none;}

	#move{width:160px;height:160px;background:url('./bg.png');position:absolute;left:0px;top:0px;display:none;}

	#bigImg{position:absolute;}

	#uls{width:400px;height:100px;position:absolute;left:100px;top:460px;}

	#uls li{width:80px;height:80px;border:solid 1px purple;list-style:none;float:left;margin-right:5px;}



	</style>
</head>
<body>
	<div id='small'><img src="./1.jpg" alt="" width='100%' id='smallImg'><div id='move'></div></div>

	<ul id='uls'>
		<li><img src="./1.jpg" alt="" width='100%'></li>
		<li><img src="./2.jpg" alt="" width='100%'></li>
		<li><img src="./3.png" alt="" width='100%'></li>
		<li><img src="./4.png" alt="" width='100%'></li>
	</ul>

	<div id='big'><img src="./1.jpg" alt="" id='bigImg'></div>

	<script type="text/javascript">
	var small = document.getElementById('small');

	var move  = document.getElementById('move');
	var bigImg = document.getElementById('bigImg');
	var big = document.getElementById('big');
	var smallImg = document.getElementById('smallImg');

	small.onmousemove = function(e)
	{
		move.style.display= 'block';

		big.style.display = 'block';
		//获取x和y坐标
		var x = e.pageX;
		var y = e.pageY;

		//获取small左部偏移量和顶部的偏移量
		var sl = small.offsetLeft;
		var st = small.offsetTop;

		//获取move一半的宽度
		var mhw = (move.offsetWidth)/2;
		var mhh = (move.offsetHeight)/2;
		//计算move距离左侧的偏移量和顶部的偏移量
		var ml = x-sl-mhw;
		var mt = y-st-mhh;


		var maxl = small.offsetWidth-move.offsetWidth;
		if(ml >= maxl){

			ml = maxl;
		}

		if(ml <= 0){

			ml = 0;
		}

		var maxt = small.offsetHeight-move.offsetHeight;
		if(mt >= maxt){

			mt = maxt;
		}

		if(mt <= 0){

			mt = 0;
		}


		//给move加上单位
		move.style.left = ml+'px';
		move.style.top = mt+'px';

		//获取大图距离big的左偏移量和顶部的偏移量
		var bl = (ml/small.offsetWidth)*bigImg.offsetWidth;
		var bt = (mt/small.offsetHeight)*bigImg.offsetHeight;

		//给大图加上单位
		bigImg.style.left = -bl+'px';
		bigImg.style.top = -bt+'px';

	}
	//鼠标移除事件
	move.onmouseout = function()
	{
		move.style.display = 'none';

		big.style.display = 'none';
	}

	//获取img元素
	var imgs = document.getElementById('uls').getElementsByTagName('img');

	for (var i = 0; i < imgs.length; i++) {
		
		imgs[i].onclick = function()
		{
			//获取点击的src
			var srcs = this.src;
			//
			bigImg.src = srcs;
			smallImg.src = srcs;


		}
	};

	//console.log(imgs); 
	</script>
</body>
</html>